<template>
    <div>
        <div class="btn">
            <el-button type="primary" @click="addGoods">添加商品</el-button>
        </div>
        <!--筛选区域-->
        <el-row :gutter="20">
            <el-col :span="24">
                <el-input v-model="form.name" clearable placeholder="请输入商品名称" style="max-width: 220px;" @clear="_getGiftList(1)"></el-input>
                <el-input v-model="form.number" clearable placeholder="请输入商品编码" style="max-width: 220px;" @clear="_getGiftList(1)"></el-input>
<!--                <el-select v-model="form.cate" clearable placeholder="请选择用户">-->
<!--                    <el-option-->
<!--                            v-for="item in cateList"-->
<!--                            :key="item.id"-->
<!--                            :label="item.name"-->
<!--                            :value="item.id">-->
<!--                    </el-option>-->
<!--                </el-select>-->
                <el-button type="primary" style="float: right" plain @click="_getGiftList(1)">查询</el-button>
            </el-col>
        </el-row>

        <!--表格开始-->
        <el-table :data="tableData" v-loading="loading" style="width: 100%;margin-top: 15px;" :header-cell-style="{background:'#eef1f6',color:'#606266'}" @selection-change="handleSelectionChange">
<!--            <el-table-column type="selection" width="55"></el-table-column>-->
            <el-table-column label="商品编码" prop="number"></el-table-column>
            <el-table-column label="商品名称" prop="name"></el-table-column>
            <el-table-column label="商品分类" prop="sname"></el-table-column>
            <el-table-column label="商品图片">
                <template slot-scope="scope">
                    <img :src="scope.row.image" alt="" style="width: 40px;height: 40px;border-radius: 4px">
                </template>
            </el-table-column>
            <el-table-column label="市场价（元）" prop="price"></el-table-column>
            <el-table-column label="库存" prop="total"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="操作" width="160">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="primary"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <Pagination @handleClickPage="currentPage" :total="total - 0"></Pagination>

        <!--新建商品的dialog-->
        <el-dialog
            :visible.sync="goodsAddDialog"
            width="50%"
            @close="goodsAddDialogClose">
            <!--这里的插槽会替换title显示的内容-->
            <div slot="title" class="header-title">
                <p class="title-name">添加商品</p>
                <!--<p class="title-info">自定义商品名称</p>-->
            </div>
            <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品编码" prop="number">
                    <el-input v-model="addForm.number" placeholder="请输入商品编码"  style="width: 304px"></el-input>
                </el-form-item>
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入商品名称"  style="width: 304px"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="sid">
                    <el-select v-model="addForm.sid" clearable placeholder="请选择用户"  style="width: 304px">
                        <el-option
                                v-for="item in sortList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="换课节数" prop="class_num">
                    <el-input v-model="addForm.class_num" placeholder="请输入换课数"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="addForm.price" placeholder="请输入价格"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="total">
                    <el-input v-model="addForm.total" placeholder="请输入库存"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" prop="image">
                    <el-upload
                            class="avatar-uploader"
                            action=""
                            :show-file-list="false"
                            accept=".jpeg,.jpg,.png"
                            :http-request="upGoodsImg">
                        <img v-if="addForm.image" :src="addForm.image" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="goodsAddDialog = false">取 消</el-button>
                <el-button type="primary" @click="save">保 存</el-button>
            </span>
        </el-dialog>

        <!--编辑商品的dialog-->
        <el-dialog
                :visible.sync="goodsEditDialog"
                width="50%">
            <!--这里的插槽会替换title显示的内容-->
            <div slot="title" class="header-title">
                <p class="title-name">编辑商品</p>
                <!--<p class="title-info">自定义商品名称</p>-->
            </div>
            <el-form :model="editForm" :rules="addRules" ref="editForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品编码" prop="number">
                    <el-input v-model="editForm.number" placeholder="请输入商品编码"  style="width: 304px"></el-input>
                </el-form-item>
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="editForm.name" placeholder="请输入商品名称"  style="width: 304px"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="sid">
                    <el-select v-model="editForm.sid" clearable placeholder="请选择用户"  style="width: 304px">
                        <el-option
                                v-for="item in sortList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="换课节数" prop="class_num">
                    <el-input v-model="editForm.class_num" placeholder="请输入换课数"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="editForm.price" placeholder="请输入换课数"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="total">
                    <el-input v-model="editForm.total" placeholder="请输入换课数"  style="width: 304px" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" prop="image">
                    <el-upload
                            class="avatar-uploader"
                            action=""
                            :show-file-list="false"
                            accept=".jpeg,.jpg,.png"
                            :http-request="upGoodsImg">
                        <img v-if="editForm.image" :src="editForm.image" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="goodsEditDialog = false">取 消</el-button>
                <el-button type="primary" @click="editSave">保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import Pagination from '../../components/pagination'
    import { getGiftList, uploadImage, giftSortList, addGoods, editGoods, delGoods } from '../../api/categoryApi'
    export default {
        name: "goods-management",
        data () {
            return {
                form: {
                    name: '',
                    number: ''
                },
                tableData: [],
                total: '',
                loading: true,
                page: 1, // 页数
                goodsAddDialog: false,
                addForm: {
                    number: '',
                    name: '',
                    sid: '',
                    class_num: '',
                    price: '',
                    total: '',
                    image: ''
                },
                addRules: {
                    number: [
                        { required: true, message: '请输入商品编码', trigger: 'blur' },
                    ],
                    name: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                    ],
                    sid: [
                        { required: true, message: '请选择商品分类', trigger: 'change' },
                    ],
                    class_num: [
                        { required: true, message: '请输入换课数', trigger: 'blur' },
                    ],
                    price: [
                        { required: true, message: '请输入价格', trigger: 'blur' },
                    ],
                    total: [
                        { required: true, message: '请输入库存', trigger: 'blur' },
                    ],
                    image: [
                        { required: true, message: '请上传商品图片', trigger: 'change' },
                    ],
                }, // 效验规则
                sortList: [], // 商品分类
                goodsEditDialog: false,
                editForm: {},
                multipleSelection: []
            }
        },
        created() {
            this._getGiftList(this.page) // 获取礼品列表
        },
        methods: {
            // 获取礼品列表
            async _getGiftList(page) {
                let params = {p: page, length: 10,name: this.form.name, number: this.form.number}
                const res = await getGiftList(params)
                if (res.code === 0) {
                    console.log(res)
                    this.tableData = res.data.list
                    this.total = res.data.total
                    this.loading = false
                }
            },
            // 添加商品
            addGoods() {
                this._giftSortList('add')
            },
            async _giftSortList(data) {
                // 获取商品分类
                const res = await giftSortList()
                if (res.code === 0) {
                    console.log(res)
                    this.sortList = res.data.list
                    data === 'add' ? this.goodsAddDialog = true : this.goodsEditDialog = true
                }
            },
            // 分页的 当前点击的页数
            currentPage(newPage) {
                console.log(`当前页: ${newPage}`)
                this.page = newPage
                this._getGiftList(this.page) // 获取礼品分类列表
            },
            // 添加商品分类的dialog关闭
            goodsAddDialogClose() {
                this.$refs.addForm.resetFields()
            },
            // 添加商品的上传图片
            async upGoodsImg(params) {
                const file = params.file
                console.log(file.type)
                // console.log(data)
                console.log(file.type === 'image/jpeg')
                if (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png') {
                    const form = new FormData()
                    form.append("image", file)
                    const res = await uploadImage(form)
                    if (res.code === 0) {
                        this.$message.success('图片上传成功')
                        console.log(res)
                        this.editForm.id ? this.editForm.image = res.data.filename : this.addForm.image = res.data.filename
                    }
                } else {
                    this.$message.warning('图片只能是 JPG 或者 PNG 格式')
                    // return false
                }
            },
            // 编辑
            handleEdit(index, row) {
                console.log(row)
                this.editForm = row
                this.editForm.id = row.id
                this._giftSortList('edit')
            },
            // 删除
            handleDel(index, row) {
                console.log(index, row)
                let arr = []
                arr.push(row.id)
                let params = {ids: arr, delete: 1}
                this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const res = await delGoods(params)
                    if (res.code === 0) {
                        this.$message.success('删除成功!')
                        this._getGiftList(this.page) // 获取礼品分类列表
                    }
                }).catch(() => {
                    this.$message.info('已取消删除')
                })
            },
            // 添加商品保存
            save() {
                console.log(this.addForm)
                this.$refs.addForm.validate(async valid => {
                    if (!valid) return false
                    console.log(valid)
                    let form = {...this.addForm}
                    // class_num: '',
                    // price: '',
                    // total: '',
                    form.class_num = form.class_num - 0
                    form.price = form.price - 0
                    form.total = form.total - 0
                    // const res = await addGoods(this.addForm)
                    const res = await addGoods(form)
                    if (res.code === 0) {
                        this.$message.success('添加成功')
                        console.log(res)
                        this.goodsAddDialog = false
                        this._getGiftList(1) // 获取礼品列表
                    }
                })
            },
            async editSave() {
                delete this.editForm.remark
                delete this.editForm.sname
                console.log(this.editForm)
                const res = await editGoods(this.editForm)
                if (res.code === 0) {
                    this.$message.success('修改成功')
                    this.goodsEditDialog = false
                    this._getGiftList(this.page) // 获取礼品列表
                }
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            }
        },
        components: {
            Pagination
        },
    }
</script>

<style scoped lang="scss">
    .btn {
        text-align: right;
        margin-bottom: 15px;
    }
    .header-title {
        .title-name {
            font-size: 18px;
            color: #333;
            font-weight: 600;
            margin-bottom: 0;
        }
        .title-info {
            font-size: 11px;
            color: #7d7d7d;
            margin-bottom: 0;
            margin-top: 4px;
        }
    }
    .avatar-uploader {
    	border: 1px dashed #d9d9d9;
    	border-radius: 6px;
    	cursor: pointer;
    	position: relative;
    	overflow: hidden;
        width: 128px;
        height: 128px;
    }
    .avatar-uploader:hover {
    	border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 128px;
        height: 128px;
        line-height: 128px;
        text-align: center;
    }
    .avatar {
        width: 128px;
        height: 128px;
        display: block;
    }
</style>
